package com.example.withroadlogistics.Sweepcode;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.withroadlogistics.R;
import com.example.withroadlogistics.Sweepcode.android.CaptureActivity;
import com.example.withroadlogistics.model.Clock;
import com.example.withroadlogistics.until.HttpCallbackListener;
import com.example.withroadlogistics.until.HttpUtil;
import com.example.withroadlogistics.until.MySharedPreferences;
import com.example.withroadlogistics.until.constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class SweepMainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private String TAG = "ifu25";
    private Button btn_scan;//扫码
    private TextView tv_scanResult;
    private Button byn_send;//发送

    private String originAddress = constant.url+"clock/userclock";
    //    Handler是Android SDK来处理异步消息的核心类。
//    子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";

            if ("OK".equals(msg.obj.toString())){
                result = "success";
            }else if ("Wrong".equals(msg.obj.toString())){
                result = "fail";
            }else {
                String data = msg.obj.toString();
//            	Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (code.equals("0")) {
                        // result = jsonObject.getString("data");
                        //web端返回的json code data
                        Log.i(TAG, "handleMessage: wen端返回的json"+code+data+result);
                        //通过Bundle封装数据
                        Bundle bundle = new Bundle();
                         bundle.putString("msg", result);//data是通过后台返回数值进行判断，弹窗
                        Toast.makeText(SweepMainActivity.this, result, Toast.LENGTH_LONG).show();
                    }else {
                          result = jsonObject.getString("msg");
                        Toast.makeText(SweepMainActivity.this, result, Toast.LENGTH_LONG).show();//失败提示
                       // Toast.makeText(SweepMainActivity.this, "账号或用户名输入错误", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(SweepMainActivity.this, "系统异常，请重试", Toast.LENGTH_LONG).show();
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_scanResult = (TextView) findViewById(R.id.tv_scanResult);
        btn_scan = (Button) findViewById(R.id.btn_scan);
        byn_send=(Button) findViewById(R.id.btn_send);
        btn_scan.setOnClickListener(this);
        byn_send.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                //动态权限申请
                if (ContextCompat.checkSelfPermission(SweepMainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(SweepMainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    goScan();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 跳转到扫码界面扫码
     */
    private void goScan(){
        Intent intent = new Intent(SweepMainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goScan();
                } else {
                    Toast.makeText(this, "你拒绝了权限申请，可能无法打开相机扫码哟！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (!isInputValid()){
                return;
            }

            if (data != null) {
                //返回的文本内容
                final String getclockcontent = data.getStringExtra(DECODED_CONTENT_KEY);
                final String routeid = (String) MySharedPreferences.getRouteid(SweepMainActivity.this);
                //返回的BitMap图像
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                Toast.makeText(getApplicationContext(), "获取"+routeid, Toast.LENGTH_SHORT).show();

                // tv_scanResult.setText("你扫描到的内容是：" + content);
                tv_scanResult.setText( "你打卡的内容是："+ getclockcontent);
                //打卡是否成判断
                byn_send.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        if(getclockcontent.length()<1){ //此处做判断无效（可不做判断-只有扫码成功该按钮才生效）
                            Toast.makeText(getApplicationContext(), "打卡失败，请重新扫码上传", Toast.LENGTH_SHORT).show();
                        }else {

                            //扫到的相关内容
                            String str =getclockcontent;
                            //提取扫码内容的相关文本
                            String[]  strs=str.split(":");
                            for(int i=0,len=strs.length;i<len;i++){
                                System.out.println("全部："+strs[i].toString());
                            }
                            String test1=strs[1].toString();
                            String clockcontent=strs[2].toString();//站点获取
                            System.out.println("测试1："+test1);
                            System.out.println("测试2："+clockcontent);
                            //二次提取二维码编号
                            String test3 = test1;
                            String qrcodeid= test3.substring(0, test3.indexOf("打"));
                            System.out.println("测试4："+qrcodeid);

                             String routeid = (String) MySharedPreferences.getRouteid(SweepMainActivity.this);
                            HashMap<String, String> params = new HashMap<String, String>();
                            params.put(Clock.ROUTEID, routeid);
                            params.put(Clock.CLOCKCONTENT, clockcontent);
                            params.put(Clock.QRCODEID, qrcodeid);
                            try {
                                String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);
                                HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                                    @Override
                                    public void onFinish(String response) {
                                        Message message = new Message();
                                        message.obj = response;
                                        mHandler.sendMessage(message);
                                    }

                                    @Override
                                    public void onError(Exception e) {
                                        Message message = new Message();
                                        message.obj = e.toString();
                                        mHandler.sendMessage(message);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                           // Toast.makeText(getApplicationContext(), "已成功打卡", Toast.LENGTH_SHORT).show();
                        }
                    }

                });

            }

        }
    }

    private boolean isInputValid() {
        //检查用户输入的合法性，这里暂且默认用户输入合法
        return true;
    }


}
